;*****************************************************
; 	Copyright (C) SEIKO EPSON CORP. 2002
;	All rights Reserved
;
;	File name : strtok.s
;	Function  :
;	       This is strtok function
;	Revision  :
;		2002/12/19	T.Tazaki for GNU33(Linux)
;
;*****************************************************

;*****************************************************
; strtok
;	a sequence of calls to strtok will break src1
;	(0 terminated) into a sequence of tokens delimited
;	by any character from src2 (0 terminated)
;
; arguments : %r6:src1 addr, %r7:src2 addr
; return    : %r4:addr of token
; comment   : destroy %r5,%r8,%r9,%r10,%r11
;*****************************************************

	.local _$$$str_pt
	.comm _$$$str_pt, 4, 4

	.section .text
	.align 1
	.global strtok
	.type	strtok,@function


strtok:
	xld.w	%r5,_$$$str_pt
	cmp		%r6, 0		; if src1 = NULL then use saved addr
	jrne	notnull

	ld.w	%r6, [%r5]

notnull:
	ld.w	%r4, 0		; initialize as NULL

	; first step: find first character in src1 that is NOT
	;	  in src2, return NULL if not found

strtok_loop:
	ld.ub	%r10, [%r6]+	; load byte
	cmp		%r10, 0
	jreq	strtok_nul_ret
	ld.w	%r11, %r7		; temp = cmp addr

cmp_loop:
	ld.ub	%r9, [%r11]+	; load byte
	cmp		%r9, %r10
	jreq	strtok_loop
	cmp		%r9, 0		; loop until end of string
	jrne	cmp_loop

	; if reaches here then found first char not in src2
	sub		%r6, 1
	ld.w	%r4, %r6

	; second step: find first character in src1 after first step
	;	   that IS in src2, return %r10 if not found

strcspn_loop:
	ld.ub	%r10, [%r6]+	; load byte
	cmp		%r10, 0
	jreq	strtok_nul_ret
	ld.w	%r11, %r7		; temp = cmp addr

cmp_loop2:
	ld.ub	%r9, [%r11]+	; load byte
	cmp		%r9, %r10
	jreq	strcspn_end
	cmp		%r9, 0		; loop until end of string
	jrne	cmp_loop2
	jp		strcspn_loop

strtok_nul_ret:
	ld.w	%r6,0
	jp		strtok_ret

strcspn_end:
	ld.w	%r10, %r6
	sub		%r10, 1		; get addr of char
	ld.w	%r8, 0
	ld.b	[%r10], %r8	; add NULL terminate

strtok_ret:
	ld.w	[%r5], %r6	; save for next use
	ret
